/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package connection;

import connection.gui.ConfigForm;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Tngoc
 */
public class Configuration {

    public Property getProp() {
        return prop;
    }

    public void setProp(Property prop) {
        this.prop = prop;
    }
    private static Property prop;
    private String path;

    public Configuration(String path) {
        this.path = path;
    }
    
    public Configuration() {
        this.path = "config.dat";
    }

    public Connection getConnect() {
        try {
            this.prop = loadProperty();
            String connectionString = "jdbc:sqlserver://" + prop.host + ";databaseName=" + prop.database;
            Connection conn = DriverManager.getConnection(connectionString, prop.userName, prop.password);
            return conn;
        } catch (SQLException ex) {
            return null;
        }
    }

    public void saveProperty(String host, String database, String username, String passwordS) {
        try {
            if(prop==null){
                prop = new Property();
            }
            prop.setHost(host);
            prop.setDatabase(database);
            prop.setUserName(username);
            prop.setPassword(passwordS);
            ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
            oos.writeObject(prop);
            oos.flush();
            oos.close();
        } catch (IOException ex) {
            System.out.println("error");
        }
    }

    public Property loadProperty() {
        try {
            File file = new File(path);
            ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
            Property p = (Property) ois.readObject();
            ois.close();
            return p;
        } catch (ClassNotFoundException ex) {
            return new Property();
        } catch (IOException ex) {
            return new Property();
        }
    }
}
